package com.fengchao.util;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;


/**
 * Created by http://my.oschina.net/wangnian on 2016/7/19.
 */
@Component
public class PushTools {

    @Autowired
    private Environment env;
    private static Logger logger = LoggerFactory.getLogger(PushTools.class);

    public Boolean Push(PushPayload payload) {
        JPushClient jpushClient = new JPushClient(env.getProperty("jpush.masterSecret"), env.getProperty("jpush.appKey"));
        try {
            PushResult result = jpushClient.sendPush(payload);
            logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            logger.error("Connection error, should retry later", e);
            MailTools.SendMail("wangn@letswarm.com", "推送错误", "异常:" + e);
            return false;
        } catch (APIRequestException e) {
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            MailTools.SendMail("wangn@letswarm.com", "推送错误", "HTTP Status: " + e.getStatus() + "Error Code: " + e.getErrorCode() + "Error Message: " + e.getErrorMessage());
            return false;
        }
        return true;
    }


    /**
     * 给所有的平台 用户发送信息
     *
     * @return
     */
    public PushPayload buildPushObject_all_all_alert(String alertText) {
        return PushPayload.alertAll(alertText);
    }

    /**
     * 给所有的平台  别名叫 [alias] 的发alertText消息
     *
     * @return
     */
    public PushPayload buildPushObject_all_alias_alert(String alertText, String alias) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.alert(alertText))
                .build();
    }
}
